package org.xxpay.pay.channel.simplepay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTrans;
import org.xxpay.pay.channel.simplepay.util.HttpClick;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class SimpleTransService extends BaseTrans {
    private final static String logPrefix = "【简单支付代付】";
    @Override
    public String getChannelName() {
        return SimplepayPayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject balance(String payParam) {
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有余额查询接口");
        return retObj;
    }

    @Override
    public JSONObject trans(TransOrder transOrder){
//        JSONObject retObj = buildRetObj();
//        Map<String, Object> transferMap = Maps.newHashMap();
//        SimplepayPayConfig config = new SimplepayPayConfig(getTransParam(transOrder));
//        setTransParams(transOrder, transferMap);
//        //设置请求参数
//        String id = config.getAppId();
//        String nonce = transferMap.get("nonce").toString();
//        String url = SimplepayPayConfig.getReqUrl("transfer")+"?id="+id+ "&nonce="+nonce;
//        String body = getData(transferMap);
//        _log.info("{}申请代付请求参数：{}", logPrefix, body);
//        String res = null;
//        try {
//            res = HttpClick.sendHttpPost(url,body,getSign(transferMap,config));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        _log.info("{}申请代付响应参数：{}", logPrefix, res);
//
//        JSONObject result = JSONObject.parseObject(res);
//        retObj.put("isSuccess", false);
//        retObj.put("transOrderId", transOrder.getTransOrderId());
//        if(StringUtils.equals(result.getString("code"),"2000")) {
//            retObj.put("channelOrderNo", "");
//            retObj.put("isSuccess", true);
//            // 1. 处理中 2. 成功 3. 失败
//            retObj.put("status", 1);
//            return retObj;
//        }
//        // 1. 处理中 2. 成功 3. 失败
//        retObj.put("status", 3);
//        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "下单失败[" + result.getString("msg") + "]");
//        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
//        return retObj;
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有代付接口，请手动下发");
        return retObj;
    }

    /**
     * 订单查询接口
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject query(TransOrder transOrder){
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有订单查询查询接口");
        return retObj;
    }
    //设置代付请求参数
    private void setTransParams(TransOrder transOrder,Map<String,Object> params){

        params.put("amount",transOrder.getAmount());
        try {
            params.put("accountName", new String(transOrder.getAccountName().getBytes(), SignUtils.CHARSET_UTF8));
            params.put("bankName", new String(transOrder.getBankName().getBytes(),SignUtils.CHARSET_UTF8));
            params.put("branchName", new String(transOrder.getBankName().getBytes(),SignUtils.CHARSET_UTF8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        params.put("bankAccount", transOrder.getAccountNo());
        params.put("nonce", System.currentTimeMillis());
    }

    /**
     * 获取请求报文
     * @param params
     * @return
     */
    private String getData(Map<String,Object> params){
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(params));
        jsonObject.remove("nonce");
        String data = jsonObject.toJSONString();
        System.out.println(data);
        return data;
    }

    /**
     * 获取sign
     * @param params
     * @return
     */
    private String getSign(Map<String,Object> params,SimplepayPayConfig config){
        String data = getData(params);

        String contents =config.getAppId()+params.get("nonce").toString()+data;
        System.out.println(contents);
        String sign=null;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(config.getPrivateKey().getBytes(),"HmacSHA256"));
            byte[] result = mac.doFinal(contents.getBytes());
            sign = bytesToHexString(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        System.out.println(sign);
        return sign;
    }
    /**
     * 获取sign
     * @param contents
     * @return
     */
    private String getSign2(String contents,SimplepayPayConfig config){
        String sign=null;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(config.getPrivateKey().getBytes(),"HmacSHA256"));
            byte[] result = mac.doFinal(contents.getBytes());
            sign = bytesToHexString(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        System.out.println(sign);
        return sign;
    }
    private  String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
